package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.util.DingdingAttendUtil;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.modular.system.entity.BtyDingdingDayDept;
import cn.stylefeng.guns.sys.modular.system.mapper.BtyDingdingDayDeptMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.BtyDingdingDayDeptParam;
import cn.stylefeng.guns.sys.modular.system.model.result.BtyDingdingDayDeptResult;
import  cn.stylefeng.guns.sys.modular.system.service.BtyDingdingDayDeptService;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dingtalk.api.response.OapiDepartmentListResponse;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.stylefeng.guns.sys.core.util.TimeUtil;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 钉钉,最新,部门,记录 服务实现类
 * </p>
 *
 * @author wjk
 * @since 2022-05-30
 */
@Service
public class BtyDingdingDayDeptServiceImpl extends ServiceImpl<BtyDingdingDayDeptMapper, BtyDingdingDayDept> implements BtyDingdingDayDeptService {


    @Resource
    private DingdingAttendUtil dingdingAttendUtil;
    
    @Override
    public void add(BtyDingdingDayDeptParam param){
        BtyDingdingDayDept entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(BtyDingdingDayDeptParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(BtyDingdingDayDeptParam param){
        BtyDingdingDayDept oldEntity = getOldEntity(param);
        BtyDingdingDayDept newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public BtyDingdingDayDeptResult findBySpec(BtyDingdingDayDeptParam param){
        return null;
    }

    @Override
    public List<BtyDingdingDayDeptResult> findListBySpec(BtyDingdingDayDeptParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(BtyDingdingDayDeptParam param){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 开始同步东更道部门的信息
     * 月度
     * @author
     * @Date 2022-05-30
     * 钉钉 写成定时任务；
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, String> addBtyDingdingMonthDept(BtyDingdingDayDeptParam param) {

        String  lastMonth = param.getAttendYearMonth();
        if(ToolUtil.isEmpty(param.getAttendYearMonth())){
            // 若没有传参数，则默认上月月的数据
            lastMonth  = TimeUtil.getLastMonthStr();
        }




        OapiDepartmentListResponse rsp = dingdingAttendUtil.getDepartmentList();
        Map map = (Map) JSON.parse(rsp.getBody());
        Integer  errcode= (Integer) map.get("errcode");
        List<BtyDingdingDayDept> deptList=new ArrayList<BtyDingdingDayDept>();

        //将总部数据存储到数据库中
        BtyDingdingDayDept deptHead=new BtyDingdingDayDept();
        deptHead.setId(UUIDUtils.getId());
        deptHead.setAttendYearMonth(lastMonth);
        deptHead.setDid(Long.valueOf("1"));
        deptHead.setName("半天妖总部");
        deptHead.setPid(Long.valueOf("1"));
        deptList.add(deptHead);

        if(errcode==0){
            List  departments= (List) map.get("department");
            for (int i=0;i<departments.size();i++){
                Map deptinfo=(Map) departments.get(i);
                BtyDingdingDayDept dept=new BtyDingdingDayDept();
                dept.setId(UUIDUtils.getId());
                dept.setAttendYearMonth(lastMonth);
                dept.setDid(Long.valueOf(deptinfo.get("id").toString()));
                dept.setName((String)deptinfo.get("name"));
                dept.setPid(Long.valueOf(deptinfo.get("parentid").toString()));

                deptList.add(dept);
            }
        }
        //根据月份，去删除数据当月的数据
        Integer delSize = this.baseMapper.deleteByYearMonth(lastMonth);
        simpleSqlInsertBatch(deptList);
        Map<String, String> mapResult = new HashMap<>();
        mapResult.put("size",String.valueOf(deptList.size()));
        return mapResult;
    }



    public int simpleSqlInsertBatch(List<BtyDingdingDayDept> list) {
        if (list == null || list.size() < 1) {
            return 0;
        }
        // 如果提交的列表条数小于提交阀值
        List<BtyDingdingDayDept>[] splitLists = splitLists(list, 300);
        for (List<BtyDingdingDayDept> tempList : splitLists) {
            this.baseMapper.addList(tempList);
            //this.saveBatch(tempList);
        }
        return list.size();
    }

    /**
     * 对一个列表按照splitNum进行分割。
     *
     * @param lists
     * @param splitNum
     * @param <T>
     * @return
     */
    public static <T>List<BtyDingdingDayDept>[] splitLists(List<BtyDingdingDayDept> lists, int splitNum) {
        int listSize;
        if (lists == null || (listSize = lists.size()) < 1) {
            return new ArrayList[0];
        }
        int length = listSize % splitNum == 0 ? listSize / splitNum : listSize / splitNum + 1;
        // 这里面如果用ArrayList，会在50行报错。ArrayList list = new List();这样会报错。
        List<BtyDingdingDayDept>[] results = new List[length];
        int fromIndex, toIndex;
        for (int i = 0; i < length; i++) {
            fromIndex = i * splitNum;
            toIndex = (fromIndex + splitNum) > listSize ? listSize : (fromIndex + splitNum);
            results[i] = lists.subList(fromIndex, toIndex);
        }
        return results;
    }






    /**
     * 获取半天妖所有的部门列表（所有，不分页）
     *
     * @Date 2022-04-14
     * @return
     */
    @Override
    public List<BtyDingdingDayDept> listMonthAll(BtyDingdingDayDeptParam param) {
        LambdaQueryWrapper<BtyDingdingDayDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BtyDingdingDayDept::getAttendYearMonth,  param.getAttendYearMonth());
        List<BtyDingdingDayDept> list = this.list(queryWrapper);
        return list;
    }


    /**
     * 查找区域
     * @param param
     * @return
     */
    @Override
    public ResponseData qyList(BtyDingdingDayDeptParam param) {
        if (ToolUtil.isNotEmpty(param.getAttendYearMonth())){
            String[] split = param.getAttendYearMonth().split("-");
            String month = split[0] + split[1];
            param.setAttendYearMonth(month);
        }
        List<BtyDingdingDayDeptResult> list = baseMapper.getQyList(param);
        return ResponseData.success(list);
    }

    private Serializable getKey(BtyDingdingDayDeptParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private BtyDingdingDayDept getOldEntity(BtyDingdingDayDeptParam param) {
        return this.getById(getKey(param));
    }

    private BtyDingdingDayDept getEntity(BtyDingdingDayDeptParam param) {
        BtyDingdingDayDept entity = new BtyDingdingDayDept();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
